import logging

from django.contrib.auth.models import User as AuthUser
from django.core.exceptions import ObjectDoesNotExist

from django.db import transaction
from django.db.models import Model
from django.core.exceptions import ObjectDoesNotExist

from blog import dao
from .models import Site, SiteTaxonomy, CategoryTaxonomy, UserProfile, Region


_logger = logging.getLogger('book.itebooks-info')


def find_site_by(*args, ** kwargs):
    site = Site.objects.filter(*args,**kwargs).first()
    return site



def get_site(site_url, taxonomy='unknown'):
    try:
        site = Site.objects.get(url=site_url)
    except ObjectDoesNotExist:
        e = site_url.rfind('.')
        s = site_url[0:e].find('.')
        if s == -1:
            s = site_url[0:e].rfind('/')
        name = site_url[s + 1:e]
        _logger.debug('url:%s,name:%s' % (site_url, name))
        site = Site(url=site_url, name=name, taxonomy=taxonomy)
        site.save()

    return site


def get_default_region():
    region = Region.objects.first()
    if not region:
        with transaction.atomic():
            region = Region(name='Default', abbr='Default')
            region.save()
    return region


def get_user(username):
    site = dao.get_local_site()
    try:
        user = AuthUser.objects.get(username=username, profile__site=site)
    except ObjectDoesNotExist:
        user = None
    return user


def new_user(username, password, email):
    site = dao.get_local_site()
    try:
        user = AuthUser.objects.get(username=username, profile__site=site)
        return None
    except ObjectDoesNotExist:
        with transaction.atomic():
            user = AuthUser.objects.create_user(
                username, email, first_name=username, password=password)
            user.save()
            user_profile = UserProfile(user=user, site=site)
            user_profile.save()
        return user
